package com.homework.controller;

import com.homework.entity.Cat;
import com.homework.service.CatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/cat")
public class CatController {

    @Autowired
    CatService catService;

//    @RequestMapping("/add")
    @PostMapping("/add")
    public String insertCat(Cat c){
        System.out.println("insertCat");
        catService.insertCat(c);
        return "success";
    }

//    @RequestMapping("/find")
    @GetMapping("/find")
    public List<Cat> selectList(){
        System.out.println("selectList");
        return catService.selectList();
    }

//    @RequestMapping("/find/{cno}")
    @GetMapping("/find/{cno}")
    public Cat selectCat(@PathVariable Integer cno){
        System.out.println("selectCat");
        return catService.selectCat(cno);
    }

//    @RequestMapping("/update")
    @PutMapping("/edit")
    public String updateCat(@RequestBody Cat c){
        System.out.println("updateCat");
        System.out.println(c);
        catService.updateCat(c);
        return  "success";
    }

//    @RequestMapping("/delete")
    @DeleteMapping("/remove/{cno}")
    public String deleteCat(@PathVariable Integer[] cno){
        System.out.println("deleteCat");
        System.out.println(Arrays.toString(cno));
        for (Integer c : cno) {
            catService.deleteCat(c);
        }
        return  "success";
    }

//    @RequestMapping("/upload")
    @PutMapping("/upload")
    public String upload(MultipartFile file,HttpServletRequest req) throws IOException {
        System.out.println("upload");
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        String rootPath = req.getServletContext().getRealPath("/static/images");
        System.out.println(rootPath);
        String image = rootPath+"/"+fileName;
        String cno = req.getParameter("cno");
        System.out.println("cno"+cno);
        Cat cat = new Cat();
        cat.setImage(image);
        System.out.println(image);
        File newFile = new File(image);
        if (!newFile.exists()){
            newFile.mkdirs();
        }
        file.transferTo(newFile);
        System.out.println("上传成功");
        catService.upload(cat);
        return "success";
    }

}
